/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package monitor;

import co.edu.unal.satacredito.database.dao.EventLogMongoDao;
import co.edu.unal.satacredito.database.entity.EventLog;
import co.edu.unal.satacredito.database.entity.Machine;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.NamingException;

/**
 *
 * @author migueldiaz
 * @author laarguelless
 */
public class AbortedProcesses extends Thread {

    private Long TIME_OUT;
    private EventLogMongoDao instanceLog;
    private Daemon daemon;
    

    public AbortedProcesses(Long time, EventLogMongoDao instance, Daemon daemon) {
        this.TIME_OUT = time;
        this.instanceLog = instance;
    }

    @Override
    public void run() {
        while (true) {
            try {
                List<EventLog> inProgress = instanceLog.findByStateWork(0);
                for (EventLog e : inProgress) {
                    Date actual = new Date();                    
                    if (actual.getTime() - e.getStartDate().getTime() > TIME_OUT  && !isAvalaible(e.getMachine()) ) {
                        e.setStateWork(2);
                        try {
                            instanceLog.update(e.getId(), e);
                        } catch (Exception ex) {
                            Logger.getLogger(Daemon.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }

                Thread.sleep(TIME_OUT);
            } catch (Exception ex) {
                Logger.getLogger(Monitor.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("Hello from a thread!");
        }
    }
    
    /**
     * Verifica si una máquina en particular está viva 
     * o no. 
     * @param ip
     * @return 
     */
    private boolean isAvalaible(Machine machine) throws IOException, NamingException{
        List<String> machines = daemon.getAvailableMachines();
        for(String host: machines){
            if(host.equals(machine.getMachineIP())){
                return true;
            }
        }
        return false;
    }
    
}
